package com.eralink.unionuhfreader.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.eralink.unionuhfreader.MyApplication;
import com.eralink.unionuhfreader.bean.AppInfo;
import com.eralink.unionuhfreader.http.Api;
import com.eralink.unionuhfreader.http.JsonCallBack;
import com.eralink.unionuhfreader.http.Result;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okserver.download.DownloadListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApkUils {
    private Context context;
    private String app_download_url;
    public ApkUils(Context context){
        this.context=context;
    }

    public  void  checkAPP(){
        Api.checkAppInfo(new JsonCallBack<Result<AppInfo>>() {
            @Override
            public void onError(Response<Result<AppInfo>> response) {
                super.onError(response);
            }

            @Override
            public void onSuccess(Response<Result<AppInfo>> response) {
                Result<AppInfo> result = response.body();
                if (result != null && result.getCode() != null && result.getCode().equals("0")) {
                    AppInfo appInfos = result.getData();
                    if (appInfos != null) {
                        PackageManager manager =context.getPackageManager();
                        try {
                            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
                            String localVersionName = info.versionName; // 版本名
                            int localVersionCode = info.versionCode; // 版本号
                            int ser_code = Integer.valueOf(appInfos.getVerCode());
                            if (ser_code > localVersionCode) {
                                //弹出升级框
                                app_download_url = appInfos.getUrl();
                                showUpdateDialog(appInfos);
                            }else{
                                // ToastUtils.showToast("您的APP已经是最新版"+info.versionName);
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    private void showUpdateDialog(AppInfo appInfo) {
        AlertDialog.Builder  builder  =  new AlertDialog.Builder(context);//使用内部的静态Builder类创造builder对象
        builder.setMessage(appInfo.getDescription()).setTitle(appInfo.getName());
        builder.setNegativeButton("确定更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                startDownload();
                dialogInterface.dismiss();
            }
        }).setPositiveButton("一定要更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                startDownload();
                dialogInterface.dismiss();
            }
        });
        AlertDialog ad = builder.create();//使用builder调用create方法得到一个AlertDialog的实例

        ad.setCanceledOnTouchOutside(false);//设置此方法为点击其他区域dialog不消失，设置为true是消失

        ad.show();//展示dialog。。。这里注意千万不要调用builder.show();方法。我就是犯了这个错误。
    }

    ProgressDialog downDialog;
    //开始下载
    private void startDownload() {
        downDialog=new ProgressDialog(context);
        downDialog.setCancelable(false);
        downDialog.setTitle("下载更新");
        downDialog.setMessage("正在下载");
        downDialog.setMax(100);

        downDialog.show();
        // 更新进度
        appFileName=app_download_url.substring(app_download_url.lastIndexOf("/")+1,app_download_url.length());

        /*if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 获得存储卡的路径
            mSavePath = Environment.getExternalStorageDirectory() + "/" + "download";
        } else {
            mSavePath = MyApplication.getRootPathOfWebAppData()+"/download";
        }


        Config config = new Config();
        //set database path.
        //    config.setDatabaseName("/sdcard/a/d.db");
        //      config.setDownloadDBController(dbController);

        //set download quantity at the same time.
        config.setDownloadThread(1);

        //set each download info thread number
        config.setEachDownloadThread(4);

        // set connect timeout,unit millisecond
        config.setConnectTimeout(10000);

        // set read data timeout,unit millisecond
        config.setReadTimeout(10000);

        DownloadManager downloadManager = DownloadService.getDownloadManager(context.getApplicationContext(),config);
        final DownloadInfo downloadInfo = new DownloadInfo.Builder().setUrl(app_download_url)
                .setPath(mSavePath+"/cash.apk")
                .build();
        downloadInfo.setDownloadListener(new com.ixuea.android.downloader.callback.DownloadListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onWaited() {

            }

            @Override
            public void onPaused() {

            }

            @Override
            public void onDownloading(long progress, long size) {
              String ss= formatFileSize(progress) + "/" + formatFileSize(size);
                int ii=(int) ((progress/size)*100);
                downDialog.setProgress(ii);
                downDialog.setMessage(ss);
                Log.d("ykj","下载进度"+progress+" ::"+size+"==="+ii);
            }

            @Override
            public void onRemoved() {

            }

            @Override
            public void onDownloadSuccess() {
                File file=new File(mSavePath+"/cash.apk");
                installApk(file);
            }

            @Override
            public void onDownloadFailed(DownloadException e) {

            }
        });

        downloadManager.download(downloadInfo);*/
        new DownloadApkThread(app_download_url).start();
       /* DownloadTask task;
        GetRequest<File> request = OkGo.get(app_download_url);
        task = OkDownload.request(app_download_url, request)
                .save().register(new ListDownloadListener(app_download_url));
        task.start();*/
    }

    private class ListDownloadListener extends DownloadListener {

        ListDownloadListener(Object tag) {
            super(tag);
        }

        @Override
        public void onStart(Progress progress) {
        }

        @Override
        public void onProgress(Progress progress) {
            Log.d("ykj",progress.currentSize+"---"+progress.totalSize+"---"+progress.fraction);
            ((Activity)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int ii=(int) (progress.fraction*100);
                    downDialog.setProgress(ii);
                    downDialog.setMessage("正在下载"+ii+"/100");
                }
            });

        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null) throwable.printStackTrace();
        }

        @Override
        public void onFinish(File file, Progress progress) {
            downDialog.dismiss();
            //下载完成
            installApk(file);
        }

        @Override
        public void onRemove(Progress progress) {
        }
    }

    private   void installApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //File file = new File(downloadApk);
        Log.i("ykj","安装路径==" );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context,  "com.jiayuan.casher.s.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }


    /*********新的下载器************************************************/
    //下载安装包中
    private static final int DOWNLOAD_APK = 1;

    //下载安装包结束
    private static final int DOWNLOAD_APK_FINISH = 2;
    //下载apk保存路径
    private String mSavePath;
    private String appFileName;
    //是否取消更新
    private boolean cancelUpdate = false;
    //记录进度数
    private int progress = 0;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_APK:
                    // 开始下载安装包
                    // 设置进度条位置
                    downDialog.setProgress(progress);
                    downDialog.setMessage("正在下载"+progress+"%");

                    //mProgress.setProgress(progress);
                    //tv_progress.setText(progress + "%");
                    break;

                case DOWNLOAD_APK_FINISH:
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    private class DownloadApkThread extends Thread {
        private String downloadUrl;
        public DownloadApkThread(String url){
            this.downloadUrl = url;
        }

        @Override
        public void run() {
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                Looper.prepare();

                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    mSavePath = Environment.getExternalStorageDirectory() + "/" + "download";
                } else {
                    mSavePath = MyApplication.getRootPathOfWebAppData()+"/download";
                }
                URL url = new URL(downloadUrl);
                // 创建连接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                // 获取文件大小
                int length = conn.getContentLength();
                // 创建输入流
                is = conn.getInputStream();

                File file = new File(mSavePath);
                // 判断文件目录是否存在
                if (!file.exists()) {
                    file.mkdir();
                }
                File apkFile = new File(mSavePath, appFileName);
                fos = new FileOutputStream(apkFile);
                int count = 0;
                // 缓存
                byte buf[] = new byte[1024];
                // 写入到文件中
                do {
                    int readNum = is.read(buf);
                    count += readNum;
                    // 计算进度条位置
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    mHandler.sendEmptyMessage(DOWNLOAD_APK);
                    if (readNum <= 0) {
                        // 下载完成
                        mHandler.sendEmptyMessage(DOWNLOAD_APK_FINISH);
                        break;
                    }
                    // 写入文件
                    fos.write(buf, 0, readNum);
                    fos.flush();
                } while (!cancelUpdate);// 点击取消就停止下载.
            } catch (Exception e) {
                ToastUtil.showToast("更新报错");
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /**
     * 安装APP包
     */
    private void installApk() {
        File apkFile = new File(mSavePath, appFileName);
        if (!apkFile.exists()) {
            return;
        }

        String cmd = "chmod 777 " + apkFile.toString();
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context,  "com.jiayuan.casher.s.fileprovider", apkFile);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            i.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(apkFile);
            i.setDataAndType(uri, "application/vnd.android.package-archive");
        }

       /*
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
            i.setDataAndType(contentUri, "application/vnd.android.package-archive");
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            i.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }*/

        context.startActivity(i);

        // 关闭当前程序
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
    }

    public static String formatFileSize(long size) {
        String sFileSize = "";
        if (size > 0) {
            double dFileSize = (double) size;

            double kiloByte = dFileSize / 1024;
            if (kiloByte < 1 && kiloByte > 0) {
                return size + "Byte";
            }
            double megaByte = kiloByte / 1024;
            if (megaByte < 1) {
                sFileSize = String.format("%.2f", kiloByte);
                return sFileSize + "K";
            }

            double gigaByte = megaByte / 1024;
            if (gigaByte < 1) {
                sFileSize = String.format("%.2f", megaByte);
                return sFileSize + "M";
            }

            double teraByte = gigaByte / 1024;
            if (teraByte < 1) {
                sFileSize = String.format("%.2f", gigaByte);
                return sFileSize + "G";
            }

            sFileSize = String.format("%.2f", teraByte);
            return sFileSize + "T";
        }
        return "0K";
    }
}
